<template>
  <div class="sample-list">
    <div class="search-bar">
      <div class="search-input-wrapper">
        <i class="fas fa-search search-icon"></i>
        <input
          type="text"
          placeholder="搜索关键字"
          v-model="searchKeyword"
        />
      </div>
      <div class="button-group">
        <button @click="exportExcel">导出Excel</button>
        <button @click="backToPreviousPage">返回</button>
      </div>
    </div>

    <div class="tab-container">
      <button
        v-for="tab in tabs"
        :key="tab.value"
        :class="{ 
          'active': currentTab === tab.value,
          'tab-button': true
        }"
        @click="switchTab(tab.value)"
      >
        {{ tab.label }}
      </button>
    </div>

    <div v-if="!isLoading" class="table-container">
      <table>
        <thead>
          <tr align="center">
            <th>序号</th>
            <th>标准名称</th>
            <th>样品名称</th>
            <th>生产厂家</th>
            <th>规格型号</th>
            <th>请需求</th>
            <th>申请人</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in paginatedSamples" :key="item.spoId">
            <td>{{ (currentPage - 1) * itemsPerPage + index + 1 }}</td>
            <td>{{ item.staName }}</td>
            <td>{{ item.spName }}</td>
            <td>{{ item.spFactory }}</td>
            <td>{{ item.spGg }}</td>
            <td>{{ item.spoNeed }}</td>
            <td>{{ item.uRealName }}</td>
            <td>
              <span 
                class="status-tag" 
                :class="item.spoStatus === '已发放' ? 'status-issued' : 'status-unissued'"
              >
                {{ item.spoStatus }}
              </span>
            </td>
            <td>
              <button
                v-if="item.spoStatus === '未发放'"
                @click="completeDistribution(item)"
                class="complete-button"
              >
                完成发放
              </button>
              <button
                v-else
                @click="deleteItem(item)"
                class="delete-button"
              >
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      <div class="pagination-container">
        <Pagination
          :current-page.sync="currentPage"
          :total-items="filteredSamples.length"
          :items-per-page.sync="itemsPerPage"
          @page-changed="handleCurrentChange"
          @items-per-page-changed="handleSizeChange"
        />
      </div>
    </div>

    <div v-else class="loading-container">
      加载中...
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import Pagination from "@/components/Pagination.vue"

export default {
  components: {
    Pagination
  },
  data() {
    return {
      searchKeyword: '',
      currentTab: 'unissued',
      samples: [],
      currentPage: 1,
      itemsPerPage: 10,
      isLoading: false,
      tabs: [
        { label: '未发放', value: 'unissued' },
        { label: '已发放', value: 'issued' }
      ]
    }
  },
  computed: {
    filteredSamples() {
      if (!this.searchKeyword) {
        return this.samples;
      }

      const keyword = this.searchKeyword.toLowerCase();
      return this.samples.filter(sample => 
        sample.staName?.toLowerCase().includes(keyword) ||
        sample.spName?.toLowerCase().includes(keyword) ||
        sample.spFactory?.toLowerCase().includes(keyword) ||
        sample.spGg?.toLowerCase().includes(keyword) ||
        sample.spoNeed?.toLowerCase().includes(keyword) ||
        sample.uRealName?.toLowerCase().includes(keyword)
      );
    },
    paginatedSamples() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.filteredSamples.slice(start, end);
    }
  },
  methods: {
    handleCurrentChange(page) {
      if (page === this.currentPage) return;
      this.currentPage = page;
    },
    handleSizeChange(size) {
      if (size === this.itemsPerPage) return;
      this.itemsPerPage = size;
      this.currentPage = 1;
    },
    async switchTab(tabValue) {
      if (this.currentTab === tabValue) return;
      this.currentTab = tabValue;
      this.currentPage = 1;
      this.searchKeyword = '';
      await this.fetchSamples();
    },
    async fetchSamples() {
      this.isLoading = true;
      try {
        const response = await axios.get(
          this.currentTab === 'issued' 
            ? 'http://localhost:8081/orders/samples/completed'
            : 'http://localhost:8081/orders/samples/pending'
        );
        this.samples = response.data;
      } catch (error) {
        console.error('获取样品数据失败:', error);
        this.$message.error('获取数据失败');
      } finally {
        this.isLoading = false;
      }
    },
    async exportExcel() {
      try {
        let url;
        if (this.currentTab === 'issued') {
          url = 'http://localhost:8081/orders/exportCompletedSamples';
        } else {
          url = 'http://localhost:8081/orders/exportPendingSamples';
        }
        const response = await axios.get(url, {
          responseType: 'blob', // 处理二进制数据
        });

        // 创建下载链接
        const blob = new Blob([response.data], {
          type:
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);

        // 从 Content-Disposition 头中提取文件名
        const contentDisposition = response.headers['content-disposition'];
        let fileName = 'export.xlsx';
        if (contentDisposition) {
          const fileNameMatch = contentDisposition.match(/filename="?(.+)"?/);
          if (fileNameMatch && fileNameMatch.length === 2)
            fileName = fileNameMatch[1];
        }

        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        link.remove();
      } catch (error) {
        console.error('Error exporting Excel:', error);
        alert('导出 Excel 失败。');
      }
    },
    backToPreviousPage() {
      this.$router.go(-1); // 假设您使用的是 Vue Router
    },
    async completeDistribution(item) {
      try {
        await axios.put(
          `http://localhost:8081/orders/samples/${item.spoId}/complete`
        );
        item.spoStatus = '已发放';
        alert('样品状态已更新为已发放');
      } catch (error) {
        console.error('Error completing distribution:', error);
        alert('完成发放失败。');
      }
    },
    async deleteItem(item) {
      if (!confirm('确定要删除此样品吗？')) return;
      try {
        await axios.delete(`http://localhost:8081/orders/samples/${item.spoId}`);
        const index = this.samples.findIndex(
          (sample) => sample.spoId === item.spoId
        );
        if (index !== -1) {
          this.samples.splice(index, 1);
        }
        alert('样品已成功删除');
      } catch (error) {
        console.error('Error deleting sample:', error);
        alert('删除样品失败。');
      }
    },
  },
  created() {
    this.fetchSamples();
  },
  watch: {
  }
}
</script>

<style scoped>
/* 添加 scoped 确保样式只在当前组件生效 */
.sample-list {
  font-family: Arial, sans-serif;
  color: #606266;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input-wrapper {
  position: relative;
  width: 300px;
}

.search-icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.search-bar input {
  width: 100%;
  padding: 8px 12px 8px 35px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.search-bar input:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.search-bar .button-group {
  display: flex;
  gap: 10px;
}

.search-bar button {
  padding: 8px 15px;
  border: none;
  background-color: #4caf50;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px; /* 增加按钮之间的间距 */
}

.search-bar button:hover {
  background-color: #45a049;
}

.tab-container {
  display: flex;
  margin-bottom: 15px;
}

.tab-container button {
  flex: 1;
  padding: 10px;
  border: none;
  background-color: #f1f1f1;
  color: #333;
  cursor: pointer;
  border-radius: 4px 4px 0 0;
}

.tab-container button.active {
  background-color: #ccc;
  color: white;
}

.table-container {
  border: 1px solid #ccc;
  border-radius: 0 0 4px 4px;
  overflow: hidden;
  width: 85%; /* 置度为85% */
  margin: 0 auto; /* 居中对齐 */
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 10px;
  text-align: center !important; /* 添加 !important 确保样式优先级 */
  border-bottom: 1px solid #ccc;
  vertical-align: middle; /* 确保垂直居中 */
}

th {
  background-color: #f2f2f2;
}

tr:hover {
  background-color: #f5f5f5;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

button {
  padding: 5px 10px;
  border: none;
  background-color: #4caf50;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

button.delete {
  background-color: red;
}

button.delete:hover {
  background-color: #ff5c5c;
}

/* 样品状态标签样式 */
.status-tag {
  display: inline-block;
  padding: 6px 12px;
  border-radius: 15px;
  font-size: 13px;
  font-weight: 500;
  line-height: 1;
  white-space: nowrap;
  transition: all 0.3s;
}

.status-issued {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-unissued {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

/* 状态标签悬停效 */
.status-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 表格内容溢出处理 */
td {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 鼠标悬停时显示完整内容 */
td:hover {
  overflow: visible;
  white-space: normal;
  background-color: #f5f7fa;
  position: relative;
  z-index: 1;
}

/* 添加表格行交背景色 */
tr:nth-child(even) {
  background-color: #fafafa;
}

/* 添加表格边框圆角 */
.table-container table {
  border-radius: 8px;
  overflow: hidden;
}

/* 优化按钮组样式 */
.button-group {
  display: flex;
  gap: 8px;
  justify-content: center;
}

/* 添加页面过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 状态标签样式 - 确保高优先级 */
.table-container .status-tag {
  display: inline-block;
  padding: 6px 12px;
  border-radius: 15px;
  font-size: 13px;
  font-weight: 500;
  line-height: 1;
  white-space: nowrap;
  transition: all 0.3s;
  margin: 0;
}

.table-container .status-issued {
  background-color: #f6ffed !important;
  color: #52c41a !important;
  border: 1px solid #b7eb8f !important;
}

.table-container .status-unissued {
  background-color: #fff2f0 !important;
  color: #ff4d4f !important;
  border: 1px solid #ffccc7 !important;
}

/* 确保表格样式一致 */
.table-container table {
  border-collapse: separate;
  border-spacing: 0;
}

.table-container th,
.table-container td {
  padding: 15px 12px;
  text-align: center !important;
  border-bottom: 1px solid #ebeef5;
  vertical-align: middle;
  font-size: 14px;
  color: #606266;
  transition: background-color 0.3s;
  background-color: #fff;
}

/* 添加过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 修改分页器容器样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

/* 分页器样式 - 增加优先级 */
:deep(.pagination button) {
  background-color: #409EFF !important;
  color: white !important;
  border: none;
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
}

:deep(.pagination button:disabled) {
  background-color: #c0c4cc !important;
  cursor: not-allowed;
}

:deep(.pagination button:hover:not(:disabled)) {
  background-color: #66b1ff !important;
}

/* 其他分页器相关样式 */
:deep(.pagination .page-input) {
  width: 60px;
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  text-align: center;
}

:deep(.pagination select) {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}

/* 加载状态样式 */
.loading-container {
  text-align: center;
  padding: 20px;
  color: #909399;
}

/* 表格容器样式 */
.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 分页器样式 */
:deep(.pagination button) {
  background-color: #409EFF !important;
  color: white !important;
  border: none;
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
}

:deep(.pagination button:disabled) {
  background-color: #c0c4cc !important;
  cursor: not-allowed;
}

:deep(.pagination button:hover:not(:disabled)) {
  background-color: #66b1ff !important;
}

/* 其他分页器相关样式 */
:deep(.pagination .page-input) {
  width: 60px;
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  text-align: center;
}

:deep(.pagination select) {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}
</style>
